package com.product.controller;

import com.rb.config.DeadQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

/**
 * @program: SpringBootDemos
 * @description: 订单处理器
 * @author: Kangsen
 * @create: 2021-08-24 14:50
 **/
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/add")
    public String saveOrder(){
        String msg = UUID.randomUUID().toString();
        log.error("提交订单时间 :{}",new Date());
        //rabbitTemplate.convertSendAndReceive(DeadQueueConfig.EXCHANGE_BUSINESS, DeadQueueConfig.QUEUE_BUSINESS_A, msg);
        rabbitTemplate.convertAndSend(DeadQueueConfig.EXCHANGE_BUSINESS,
                DeadQueueConfig.QUEUE_BUSINESS_A,
                msg
        );
        return "提交订单成功 =>"+msg;
    }

    @GetMapping("/submit")
    public String submitOrder(){
        String msg = UUID.randomUUID().toString();
        log.error("提交订单时间 :{}",new Date());
        rabbitTemplate.convertSendAndReceive(DeadQueueConfig.EXCHANGE_BUSINESS, DeadQueueConfig.QUEUE_BUSINESS_A, "deadLetter"+msg);
        return "提交订单成功 =>"+msg;
    }


    @GetMapping("/delay")
    public String delayOrder(){
        String msg = UUID.randomUUID().toString();
        log.error("提交延迟订单时间 :{}-{}",msg,new Date());
        //rabbitTemplate.convertSendAndReceive(DeadQueueConfig.EXCHANGE_DELAY, DeadQueueConfig.QUEUE_DELAY, msg);
        rabbitTemplate.convertAndSend(DeadQueueConfig.EXCHANGE_DELAY,//延迟交换机
                DeadQueueConfig.ROUTE_DELAY_KEY,//延迟队列路由
                msg,
                new CorrelationData()
        );
        return "提交延迟订单 =>"+msg;
    }

    @GetMapping("/delay/{delay}")
    public String delayOrder(@PathVariable("delay") Integer delay){
        String msg = UUID.randomUUID().toString();
        log.error("提交延迟订单时间 :{}-{}",msg,new Date());
        rabbitTemplate.convertAndSend(DeadQueueConfig.EXCHANGE_DELAY,//延迟交换机
                DeadQueueConfig.ROUTE_DELAY_KEY,//延迟队列路由
                msg,
                message -> {
                    message.getMessageProperties().setExpiration(String.valueOf(delay*1000));
                    return message;
                }
        );
        return "提交延迟订单 =>"+msg;
    }


}
